package org.blackcat.service.impl;

import org.blackcat.common.DESUtil;
import org.blackcat.common.PageUtils;
import org.blackcat.common.StringUtils;
import org.blackcat.common.UUIDUtils;
import org.blackcat.dao.ECGDao;
import org.blackcat.dao.redis.RedisHandle;
import org.blackcat.domain.ECG;
import org.blackcat.domain.common.MsgResponse;
import org.blackcat.domain.enums.ResponseCodeEnum;
import org.blackcat.domain.enums.UserEnum;
import org.blackcat.service.ECGService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 詹泽
 * @date 2017/2/27
 */
@Service
public class ECGServiceImpl implements ECGService {

    @Autowired
    private ECGDao ecgDao;
    @Autowired
    private RedisHandle redisHandle;

    @Override
    public MsgResponse<ECG> getECGByTime(String token, String time) throws Exception {
        String idAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(idAES, UserEnum.USER_AES_KEY.getValue());
        if(!StringUtils.regularMatch(time,"\\d{4}-\\d{1,2}-\\d{1,2}")){
            return new MsgResponse<>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR,"查询时间参数出错！");
        }
        ECG ecg = ecgDao.getECGByTime(userId,time);
        return new MsgResponse<>(ResponseCodeEnum.SUCCESS,ecg);
    }

    @Override
    public MsgResponse<Object> addECG(ECG ecg, String token) throws Exception {
        ecg.setId(UUIDUtils.uuid());
        String idAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(idAES, UserEnum.USER_AES_KEY.getValue());
        ecg.setUserId(userId);
        ecg.setGmtCreate(new Date());
        ecg.setGmtModified(new Date());
        Integer rs = ecgDao.addECG(ecg);
        if(rs != null && rs > 0){
            return new MsgResponse<>(ResponseCodeEnum.SUCCESS);
        }
        return new MsgResponse<>(ResponseCodeEnum.EXCEPTION);
    }

    @Override
    public MsgResponse<List<ECG>> listECG(String token, int pageIndex, int pageCount) throws Exception {
        String idAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(idAES, UserEnum.USER_AES_KEY.getValue());
        Integer totalCount = ecgDao.getTotalCount(userId);
        pageIndex = PageUtils.pageHelper(pageIndex,pageCount);
        List<ECG> list = ecgDao.listECG(userId,pageIndex,pageCount);
        return new MsgResponse<>(ResponseCodeEnum.SUCCESS,list,totalCount);
    }



    @Override
    public MsgResponse<Object> getECGTotalCount(String token) throws Exception {
        String idAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(idAES, UserEnum.USER_AES_KEY.getValue());
        Integer totalCount = ecgDao.getTotalCount(userId);
        return new MsgResponse<>(ResponseCodeEnum.SUCCESS,totalCount);
    }
}
